/**
 * 通用API调用工具函数
 */

/**
 * 检查响应是否为token过期
 */
export function isTokenExpired(response: any): boolean {
  // 检查响应体中的消息
  if (response.message === 'token过期') {
    return true;
  }
  
  // 检查响应体中的data字段
  if (response.data === 'token过期') {
    return true;
  }
  
  // 检查响应体中的cause字段
  if (response.cause === 'token过期') {
    return true;
  }
  
  return false;
}

/**
 * 处理token过期，自动跳转到登录页面
 */
export function handleTokenExpired(
  setMessage?: (message: string) => void,
  setSeverity?: (severity: 'success' | 'error' | 'info' | 'warning') => void
): void {
  const message = '登录已过期，正在跳转到登录页面...';
  
  console.log('handleTokenExpired called with message:', message); // 调试信息
  
  if (setMessage) {
    console.log('Setting message to:', message); // 调试信息
    setMessage(message);
  }
  
  if (setSeverity) {
    console.log('Setting severity to warning'); // 调试信息
    setSeverity('warning');
  }
  
  console.warn(message);
  
  // 清除本地存储
  console.log('Clearing localStorage'); // 调试信息
  localStorage.clear();
  
  // 延迟跳转，让用户看到提示
  console.log('Setting timeout for redirect'); // 调试信息
  setTimeout(() => {
    console.log('Redirecting to /sign-in'); // 调试信息
    window.location.href = '/sign-in';
  }, 2000);
}

/**
 * 安全的API调用
 */
export async function safeApiCall(
  url: string,
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET',
  body?: any,
  headers: Record<string, string> = {}
): Promise<{ success: boolean; data?: any; error?: string }> {
  try {
    const requestOptions: RequestInit = {
      method,
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
    };

    if (body && method !== 'GET') {
      requestOptions.body = JSON.stringify(body);
    }

    const response = await fetch(url, requestOptions);
    
    if (response.ok) {
      const data = await response.json();
      
      if (data.code === 200) {
        return { success: true, data };
      } if (isTokenExpired(data)) {
        // Token过期，返回错误信息，让调用方处理
        return { success: false, error: 'token过期' };
      } 
        // 其他错误
        const errorMessage = data.data || data.message || '操作失败';
        return { success: false, error: errorMessage };
      
    } 
      // HTTP错误处理
      // eslint-disable-next-line no-lonely-if
      if (response.status === 400) {
        // HTTP 400 可能表示Token过期，需要检查响应体
        try {
          const errorData = await response.json();
          if (isTokenExpired(errorData)) {
            console.log('HTTP 400 with token expired detected');
            return { success: false, error: 'token过期' };
          }
        } catch (e) {
          // 如果无法解析响应体，当作普通400错误处理
        }
        const errorMessage = `请求参数错误: ${response.status}`;
        return { success: false, error: errorMessage };
      } else if (response.status === 401) {
        // HTTP 401 通常表示token过期或无效，当作token过期处理
        console.log('HTTP 401 detected, treating as token expired');
        return { success: false, error: 'token过期' };
      } 
        const errorMessage = `HTTP错误: ${response.status}`;
        return { success: false, error: errorMessage };
      
    
  } catch (error) {
    console.error('API call failed:', error);
    const errorMessage = '网络请求失败';
    return { success: false, error: errorMessage };
  }
}

/**
 * 获取认证头
 */
export function getAuthHeader(): { Authorization: string } | {} {
  const token = localStorage.getItem('token');
  
  // 添加调试信息
  console.log('Getting auth header, token:', token ? `${token.substring(0, 20)}...` : 'null');
  
  if (token && token.trim() !== '') {
    // 确保token格式正确
    if (!token.startsWith('Bearer ')) {
      console.warn('Token format incorrect, should start with "Bearer "');
      return { Authorization: `Bearer ${token}` };
    }
    return { Authorization: token };
  }
  
  console.warn('No token found in localStorage');
  return {};
}

/**
 * 检查token是否存在
 */
export function hasValidToken(): boolean {
  const token = localStorage.getItem('token');
  const isValid = token !== null && token !== undefined && token.trim() !== '';
  
  console.log('Token validation:', { 
    hasToken: !!token, 
    tokenLength: token?.length, 
    isValid 
  });
  
  return isValid;
}

/**
 * 从JWT token中提取设备ID
 */
export function extractDeviceIdFromToken(): string | null {
  try {
    const token = localStorage.getItem('token');
    if (!token) return null;
    
    // 简单的JWT解析（仅用于提取设备ID）
    const payload = token.split('.')[1];
    if (!payload) return null;
    
    const decodedPayload = JSON.parse(atob(payload));
    const deviceId = decodedPayload.deviceId;
    
    console.log('Extracted deviceId from token:', deviceId);
    return deviceId;
  } catch (error) {
    console.error('Error extracting deviceId from token:', error);
    return null;
  }
}

/**
 * 从JWT token中提取用户名
 */
export function extractUsernameFromToken(): string | null {
  try {
    const token = localStorage.getItem('token');
    if (!token) return null;
    
    // 简单的JWT解析（仅用于提取用户名）
    const payload = token.split('.')[1];
    if (!payload) return null;
    
    const decodedPayload = JSON.parse(atob(payload));
    const username = decodedPayload.sub; // JWT标准中用户名在sub字段
    
    console.log('Extracted username from token:', username);
    return username;
  } catch (error) {
    console.error('Error extracting username from token:', error);
    return null;
  }
}
